import axios from 'axios'
import { Message } from 'element-ui'

// axios.defaults.withCredentials = true

export function request (config) {
  const instance = axios.create(
    {
      baseURL: 'https://knowblog.coreja.com/blog',
      timeout: 10000,
      crossDomain: true
    }
  )

  instance.interceptors.request.use(config => {
    const authorization = window.sessionStorage.getItem('authorization')
    if (authorization !== null && typeof authorization !== 'undefined') {
      config.headers.authorization = window.sessionStorage.getItem('authorization')
    }
    return config
  }, err => {
    Message.error({
      showClose: true,
      message: err.response ? err.response : '网络请求异常'
    })
  })

  instance.interceptors.response.use(res => {
    const authorization = res.headers.authorization
    if (authorization !== null && typeof authorization !== 'undefined') {
      window.sessionStorage.setItem('authorization', authorization)
    }
    // 统一异常提示
    if (res.data.code !== '00000') {
      Message.error(res.data.message)
    }
    return res
  }, err => {
    Message.error({
      showClose: true,
      message: err.response ? err.response.data.message : '网络异常'
    })
    return Promise.reject(err)
  })

  return instance(config)
}
